package com.dragon.geekbang.thinking.in.spring.ioc.container.overview.dependency.lookup;


import com.dragon.geekbang.thinking.in.spring.ioc.container.overview.anotation.Super;
import com.dragon.geekbang.thinking.in.spring.ioc.container.overview.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Map;


/**
 * 依赖查找示例
 */
public class DependencyLookupDemo {

    public static void main(String[] args) {

        // 配置 XML 配置文件
        // 启动 Spring 应用上下文
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META_INF/dependency-lookup-context.xml");

        // 实时查找
        lookupInRealTime(beanFactory);
        // 延迟查找
        lookupInLazy(beanFactory);

        // 根据类型查找
        lookupByType(beanFactory);
        // 根据类型查找集合
        lookupCollectionByType(beanFactory);
        // 根据注解查找
        lookupByAnnotation(beanFactory);

    }

    private static void lookupByAnnotation(BeanFactory beanFactory) {
        if(beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, Object> users = listableBeanFactory.getBeansWithAnnotation(Super.class);
            System.out.println("根据Annotation查找: " + users);
        }
    }

    private static void lookupCollectionByType(BeanFactory beanFactory) {
        if(beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> users = listableBeanFactory.getBeansOfType(User.class);
            System.out.println("查找所有的User对象集合: " + users);
        }
    }

    private static void lookupInRealTime(BeanFactory beanFactory){
        User user = (User) beanFactory.getBean("user");
        System.out.println("实时查找： " + user);
    }

    private static void lookupInLazy(BeanFactory beanFactory) {
        ObjectFactory<User> objectFactoryBean = (ObjectFactory<User>) beanFactory.getBean("objectFactoryBean");
        User user = objectFactoryBean.getObject();
        System.out.println("延迟查找： " + user);
    }

    private static void lookupByType(BeanFactory beanFactory) {
        User user =  beanFactory.getBean(User.class);
        System.out.println("根据类型查找： " + user);
    }

}
